(*
     camlflickr - example/interesting
     Copyright (C) 2008  Zachary R. Anderson (zanderso@gmail.com)
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation; either version 2 of the License, or
     (at your option) any later version.
 
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.
 
     You should have received a copy of the GNU General Public License along
     with this program; if not, write to the Free Software Foundation, Inc.,
     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)

(*
Authenticate, then download some "Interesting" photos into
~/Pictures.
*)

open Camlflickr
open Camlflickr.Xmlutil

module X = Xml

let (|>) (a : 'a) (f : 'a -> 'b) : 'b = f a

let webbrowser = "firefox"

let api_key = "58a83a4e789fd95dd9d31ac11d825e38"
let api_secret = "e2f973126ee0dc09"

let dlIfLarge (flickr : flickrClass) (dldir : string) (ph : photo) : unit =
    let szlst =
        try
        flickr#restUnauthCall "flickr.photos.getSizes" ["photo_id",ph.id]
        |> X.parse_string
        |> getXmlList "rsp[0].sizes[0]"
        |> List.filter (fun sz -> getXmlVal "size[label]" sz = "Large")
        with _ -> []
    in
    if szlst <> [] then
        let sz = List.hd szlst in
        let url = getXmlVal "size[source]" sz in
        downloadPhoto dldir ~url:url ph

let open_browser (url : string) : unit =
    ignore(Sys.command(webbrowser^" \""^url^"\""))

let test () : unit =
    let flickr = new flickrClass api_key api_secret in
    let (frob,token) = flickr#getTokenPartOne open_browser "read" in
    if token = "" then ignore(read_line ());
    let _ = flickr#getTokenPartTwo token frob in
    let dldir =  (Unix.getenv "HOME")^"/Pictures" in
    if not(Sys.file_exists dldir) then
        Unix.mkdir dldir 0o755;
    flickr#restUnauthCall "flickr.interestingness.getList" ["per_page","500"]
    |> X.parse_string
    |> getXmlList "rsp[0].photos[0]"
    |> List.map xmlToPhoto
    |> List.iter (dlIfLarge flickr dldir);
    Printf.printf "Success\n"

let _ = test ();;
